package com.atmilan.quartz.job;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.service.IStoreProductService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 喜洋洋商品同步
 * @Description: 
 * @author daigb
 * @date 2021-05-31
 */
@Component
@Configuration
@EnableScheduling
public class ImageDownTask {
	@Autowired
    BaseTask baseTask;
    @Autowired
    IStoreProductService storeProductService;

    public void syncTask() {
    	List<Integer> cates = Arrays.asList(1792,1793,1794,1795,1796,1797,1798,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817);
    	List<Integer> brands = Arrays.asList(88,129,152,168,239,3683,4765);
        List<StoreProduct> products = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
        		.in(StoreProduct::getBrandId, brands)
        		.in(StoreProduct::getCateId, cates)
        		.eq(StoreProduct::getIsEurope, 5)
        		.eq(StoreProduct::getIsShow, true)
        		);
        int z = 1;
        for (StoreProduct product : products) {
            JSONArray imgs = JSONArray.parseArray(product.getSliderImage());
            int i = 1;
            System.out.println("========" + z + "========");
            z++;
            
            File file = new File("d:\\商品\\" + product.getKeyword() + "\\" + 1);
            if (file.getParentFile().exists()) {
                continue;
            }
            if(null == imgs) {
            	continue;
            }
            
            for (Object url : imgs) {
                byte[] btImg = getImageFromNetByUrl(url.toString());
                if (null != btImg && btImg.length > 0) {
                    String fileName = i + ".png";
                    writeImageToDisk(btImg, fileName, product.getKeyword());
                } else {
                    System.out.println("没有从该连接获得内容");
                }

                i++;
            }
        }
    }

    /**
     * 将图片写入到磁盘
     * @param img 图片数据流
     * @param fileName 文件保存时的名称
     */
    public static void writeImageToDisk(byte[] img, String fileName, String code) {
        try {
            File file = new File("d:\\商品\\" + code + "\\" + fileName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
            System.out.println("图片已经写入");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据地址获得数据的字节流
     * @param strUrl 网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

}
